package com.kws.merchant.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.security.auth.AuthUtil;
import com.kws.merchant.domain.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.RemarkPo;
import com.kws.merchant.domain.po.ServePo;
import com.kws.merchant.domain.po.StatusCheck;
import com.kws.merchant.domain.vo.GoodsRemarkVo;
import com.kws.merchant.domain.vo.ServeVo;
import com.kws.merchant.mapper.ServeMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品-服务(Serve)表服务实现类
 *
 * @author yxy
 * @since 2024-10-22 15:57:33
 */
@Service("serveService")
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements ServeService {

    @Resource
    private ServeMapper serveMapper;
    @Autowired
    private ServeImgService serveImgService;
    @Autowired
    private GoodsViewService goodsViewService;
    @Autowired
    private DeviceRemarkService deviceRemarkService;
    @Autowired
    private OrderService orderService;
    @Autowired
    @Lazy
    private MerchantService merchantService;

    @Value("${minio.ENDPOINT}")
    private String minioUrl;
    /**
     * 分页查询列表
     *
     * @param serve
     * @return
     */
    @Override
    public Page<Serve> pageList(ServePo serve) {
        Integer pageSize = serve.getPageSize();
        Integer totalPage = serve.getTotalPage();
        String name = serve.getName();//姓名
        String type = serve.getType();//类型
        String status = serve.getStatus();//状态
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        //查询是否为商家
        boolean flag = sysUser.getCompanyId()!=null;
        String sql = " ";
        if (flag) {
            sql+=" and a.merchant_id="+sysUser.getCompanyId();
        }
        if (!StringUtils.isEmpty(name)) {
            sql += " and a.name like '%" + name+"%'";
        }
        if (!StringUtils.isEmpty(type)) {
            sql += " and a.type=" + type;
        }
        if (!StringUtils.isEmpty(status)) {
            sql += " and a.status=" + status;
        }
        int total = serveMapper.countToTal(sql);
        int sizeNum = (pageSize - 1) * totalPage;//计算分页
        //查询签名数据
        List<Serve> records = serveMapper.getRecords(sql, sizeNum, totalPage);
        records.forEach(x->{
            x.setImg(FileUtil.fixFileName()+x.getImg());
        });
        Page<Serve> page = new Page<>();
        page.setRecords(records);
        page.setTotal(total);
        page.setCurrent(pageSize);
        page.setPages((total + totalPage - 1) / totalPage);
        page.setSize(totalPage);
        return page;
    }

    @Override
    public ServeVo detailById(Long id) {
        ServeVo serveVo = new ServeVo();
        Serve serve = serveMapper.detailById(id);
        if (ObjectUtils.isEmpty(serve)){
            throw new RuntimeException("没有该商品服务");
        }
        serve.setImg(FileUtil.fixFileName()+serve.getImg());
        //根据商品服务id查询多张图片
        List<String> imgArr = serveImgService.listByServeId(id).stream().map(x -> x.getImg()).collect(Collectors.toList());
        serve.setImgArr(imgArr);
        serveVo.setServe(serve);
        //根据商品服务id查询评论
        /*List<DeviceRemark> remarkByDeviceId = deviceRemarkService.getRemarkByDeviceId(id);
        serveVo.setRemarkList(remarkByDeviceId);*/
        //根据设备计算评分，规则为平均分
        GoodsRemarkVo goodsRemarkVo = deviceRemarkService.scoreAvg(id);
        serveVo.setGoodsRemarkVo(goodsRemarkVo);
        serveVo.setType(serve.getType());//分类
        serveVo.setSuggestedPrice(serve.getPrice());//建议价格
        serveVo.setQuantity(serve.getInventory());//仓库数量
        Integer salesVolume = orderService.countByGoodsId(id);
        serveVo.setSalesVolume(salesVolume);
        return serveVo;
    }

    /**
     * 商品服务上下架
     * @param statusCheck
     * @return
     */
    @Override
    public Object updateStatus(StatusCheck statusCheck) {
        Serve serve = this.getById(statusCheck.getId());
        if (ObjectUtils.isEmpty(serve)){
            throw new RuntimeException("商品服务不存在");
        }
        if (serve.getStatus()==2){
            throw new RuntimeException("设备审核中，不能操作！！");
        }
        //上架需要审核
        if (statusCheck.getType() == 0) {
            serve.setStatus(2);
        }else if(statusCheck.getType() == 1){
            serve.setStatus(1);
        }else{
            throw new RuntimeException("设备审核中，无法上下架");
        }
        return this.updateById(serve);
    }

    /**
     * 新增服务
     * @param serve
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object addServe(Serve serve) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        serve.setImg(FileUtil.subFileName(serve.getImg()));
        serve.setMerchantId(sysUser.getCompanyId());
        //新增状态
        serve.setAuditStatus("0");
        this.save(serve);
        //默认下架
        serve.setStatus(1);
        List<String> imgArr = serve.getImgArr();
        Long serveId = serve.getId();
        //添加商品服务图片
        serveImgService.saveImgs(serveId,imgArr);
        return true;
    }

    /**
     * 商品服务评论
     * @param remarkPo
     * @return
     */
    @Override
    public Object serveRemark(RemarkPo remarkPo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        DeviceRemark deviceRemark = new DeviceRemark();
        deviceRemark.setDeviceId(remarkPo.getId());
        deviceRemark.setRemark(remarkPo.getContent());
        deviceRemark.setObserver(sysUser.getUserId());
        deviceRemark.setObserverPhone(sysUser.getPhonenumber());
        deviceRemark.setScore(remarkPo.getScore());
        deviceRemark.setTag(remarkPo.getTag());
        deviceRemark.setPid(remarkPo.getPid());
        deviceRemark.setRemarkType("0");
        deviceRemark.setOrderId(remarkPo.getOrderId());
        return deviceRemarkService.save(deviceRemark);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object updateServe(Serve serve) {
        if (serve.getStatus()!=1){
            throw new RuntimeException("商品未下架，不可修改");
        }
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        serve.setMerchantId(companyId);
        serve.setImg(FileUtil.subFileName(serve.getImg()));
        serve.setStatus(1);
        //修改商品服务
        this.updateById(serve);
        //存储商品服务图片
        List<String> imgArr = serve.getImgArr();
        Long serveId = serve.getId();
        serveImgService.saveImgs(serveId,imgArr);
        return true;
    }

    /**
     * 撤销审核
     * @param id
     * @return
     */
    @Override
    public Object repealCheck(Long id) {
        Serve serve = this.getById(id);
        serve.setStatus(1);
        return this.updateById(serve);
    }

    /**
     * 删除数据-可删除多个
     * @param idList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object removeByIdList(List<Long> idList) {
        idList.forEach(x->{
            //删除设备图片
            serveImgService.remove(Wrappers.<ServeImg>lambdaQuery().eq(ServeImg::getServeId,x));
        });
        //删除设备
        this.removeByIds(idList);
        return true;
    }

    /**
     * 商家服务列表
     * @return
     */
    @Override
    public List<Serve> listByMerchant() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        return this.list(Wrappers.<Serve>lambdaQuery().eq(Serve::getMerchantId,companyId));
    }


}
